/*
* Copyright (c) 2008 Greg Weber greg at gregweber.info
* Dual licensed under the MIT and GPLv2 licenses just as jQuery is:
* http://jquery.org/license
*
* documentation at http://gregweber.info/projects/uitablefilter
*
* allows table rows to be filtered (made invisible)
* <code>
* t = $('table')
* $.uiTableFilter( t, phrase )
* </code>
* arguments:
* jQuery object containing table rows
* phrase to search for
* optional arguments:
* column to limit search too (the column title in the table header)
* ifHidden - callback to execute if one or more elements was hidden
*/
(function($) {
  $.uiTableFilter = function(jq, phrase){

    var phrase_length = phrase.length;
    //var words = phrase.toLowerCase().split(" ");	words={"pub1":"Publisher",    "Media Type":"mediatype1"}
    var words = phrase;
    var words_length = 0;
    for(var key in words){
    	words_length++;
    	word = words[key];
    	 var index = null;
         jq.find("thead > tr:last > th").each( function(i){
           var headText = $.trim($(this).text());
           headText = headText.replace(/X/, "");
           if(headText == word ){
             index = i; return false;
           }
         });
         if( index == null ) throw("given column: " + column + " not found");
         words[key] = index;
    }
    
    
    // these function pointers may change
    var matches = function(elem) { elem.show() }
    var noMatch = function(elem) { elem.hide(); }
    var getText = function(elem) { return elem.text() }
    
    var elems = jq.find("tbody:first > tr")
    
    elems.each(function(){
		var elem = $(this);
    	var matchFlag = true;
    	if(words_length > 0){
		    for(var key in words){
		      matchFlag = $.uiTableFilter.has_words( $(elem.find(
		    	        ("td:eq(" + words[key] + ")") )).text(), key );
		      if(matchFlag == false) break;
		    }    		
    	}

	    matchFlag ? matches(elem) : noMatch(elem);
    });

    return jq;
  };

  // caching for speedup

  // not jQuery dependent
  // "" [""] -> Boolean
  // "" [""] Boolean -> Boolean
  $.uiTableFilter.has_words = function( word, filter )
  {
    if (filter == word)
    	return true;
    return false;
  }
}) (jQuery);
